package com.ruoyi.system.controller;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.reservationserver.dao.CourtDao;
import com.ruoyi.system.domain.CourtStatistic;
import com.ruoyi.reservationserver.entity.CourtType;
import com.ruoyi.system.domain.Stadium;
import com.ruoyi.reservationserver.pojo.CourtPojo;
import com.ruoyi.reservationserver.service.CourtService;
import com.ruoyi.system.service.CourtStatisticService;
import com.ruoyi.reservationserver.service.CourtTypeService;
import com.ruoyi.reservationserver.service.StadiumService;
import com.ruoyi.reservationserver.utils.Result;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Court;
import com.ruoyi.system.service.ICourtService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 场地管理Controller
 * 
 * @author guiye
 * @date 2023-08-12
 */
@RestController
@RequestMapping("/system/court")
public class CourtController extends BaseController
{

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ICourtService courtService;

    @Resource
    private CourtService courtService1;
    @Resource
    private CourtDao courtDao;

    @Resource
    private CourtTypeService courtTypeService;

    @Resource
    private CourtStatisticService courtStatisticService;

    @Resource
    private StadiumService stadiumService;




    /**
     * 根据courtType返回对应的球场列表
     * @param courtType
     * @return
     */
    @GetMapping("/selectListByCourtType")
    public TableDataInfo selectListByCourtType(@RequestParam(value = "courtType",required = true) Integer courtType ){
        List<Court> courts;
        if (redisCache.getCacheObject(CacheConstants.COURT_ACCORD_TYPE_KEY+"courtTypeId:"+courtType)!=null){
            courts=redisCache.getCacheObject(CacheConstants.COURT_ACCORD_TYPE_KEY+"courtTypeId:"+courtType);
        }else {
            courts = courtService.selectListByCourtType(courtType);
            redisCache.setCacheObject(CacheConstants.COURT_ACCORD_TYPE_KEY+"courtTypeId:"+courtType,courts);
        }
        return getDataTable(courts);
    }


    /**
     * 查询场地管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:court:list')")
    @GetMapping("/list")
    public TableDataInfo list(Court court)
    {
        startPage();
        List<Court> list = courtService.selectCourtList(court);
        return getDataTable(list);
    }

    /**
     * 导出场地管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:court:export')")
    @Log(title = "场地管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Court court)
    {
        List<Court> list = courtService.selectCourtList(court);
        ExcelUtil<Court> util = new ExcelUtil<Court>(Court.class);
        util.exportExcel(response, list, "场地管理数据");
    }

    /**
     * 获取场地管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:court:query')")
    @GetMapping(value = "/{courtId}")
    public AjaxResult getInfo(@PathVariable("courtId") Long courtId)
    {
        return success(courtService.selectCourtByCourtId(courtId));
    }

    /**
     * 新增场地管理
     */
    @PreAuthorize("@ss.hasPermi('system:court:add')")
    @Log(title = "场地管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Court court)
    {
        QueryWrapper<CourtStatistic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stadium_id",court.getStadiumId());
        CourtStatistic courtStatistic = courtStatisticService.getOne(queryWrapper);
        if (courtStatistic !=null){
            Integer courtNum = courtStatistic.getCourtNum()+1;
            courtStatistic.setCourtNum(courtNum);
            courtStatisticService.update(courtStatistic);
        }else {
            return AjaxResult.error("500","不存在该球馆");
        }
        return toAjax(courtService.insertCourt(court));
    }

    /**
     * 修改场地管理
     */
    @PreAuthorize("@ss.hasPermi('system:court:edit')")
    @Log(title = "场地管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Court court)
    {
        return toAjax(courtService.updateCourt(court));
    }

    /**
     * 删除场地管理
     */
    @PreAuthorize("@ss.hasPermi('system:court:remove')")
    @Log(title = "场地管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{courtIds}")
    public AjaxResult remove(@PathVariable Long[] courtIds) {
        for (int i = 0; i < courtIds.length; i++) {
            Long id = courtIds[i];
            Court court = courtService.selectCourtByCourtId(id);
            QueryWrapper<CourtStatistic> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("stadium_id", court.getStadiumId());
            CourtStatistic courtStatistic = courtStatisticService.getOne(queryWrapper);
            if (courtStatistic != null) {
                Integer courtNum = courtStatistic.getCourtNum() - 1;
                courtStatistic.setCourtNum(courtNum);
                courtStatisticService.update(courtStatistic);
            }

        }
        redisCache.deleteObject(CacheConstants.COURT_ACCORD_TYPE_KEY);
        return toAjax(courtService.deleteCourtByCourtIds(courtIds));
    }



    /**
     * 获取分页场地信息
     * @param page
     * @param count
     * @return
     */
    @GetMapping
    public Result index(@RequestParam(value = "page", defaultValue = "1") int page,
                        @RequestParam(value = "count", defaultValue = "10") int count) {
        PageInfo<com.ruoyi.reservationserver.entity.Court> pageInfo = courtService1.selectCourtWithPage(page, count);
        return Result.success(pageInfo);
    }

    /**
     * 通过场地名称查询场地信息
     * @param courtName
     * @return
     */
    @GetMapping("selectCourtListByCourtName")
    public Result selectCourtListByCourtName(@RequestParam String  courtName){
        List<com.ruoyi.reservationserver.entity.Court> courtList;
        if (courtName==null){
            return Result.error("不能输入空信息");
        }
        courtList = courtDao.selectCourtListByCourtName(courtName);
        return Result.success(courtList);
    }

    /**
     * 新增数据
     *
     * @param court 实体
     * @return 新增结果
     */
    @PostMapping("add")
    public Result add(@RequestBody com.ruoyi.reservationserver.entity.Court court) {
        QueryWrapper<CourtStatistic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stadium_id",court.getStadiumId());
        CourtStatistic courtStatistic = courtStatisticService.getOne(queryWrapper);
        if (courtStatistic !=null){
            Integer courtNum = courtStatistic.getCourtNum()+1;
            courtStatistic.setCourtNum(courtNum);
            courtStatisticService.update(courtStatistic);
        }else {
            return Result.error("500","不存在该球馆");
        }
        return Result.success(this.courtService1.insert(court));
    }

    /**
     * 编辑数据
     *
     * @param court 实体
     * @return 编辑结果
     */
    @PostMapping("/edit")
    public Result edit(@RequestBody com.ruoyi.reservationserver.entity.Court court) {
        System.out.println(court);
        if (court==null){
            return Result.error("返回数据不能为空");
        }

        this.courtService1.update(court);
        return Result.success();
    }

    @GetMapping("getCourtList")
    public Result getCourtList(){

        List<CourtPojo> courtPojos=new ArrayList<>();

        List<com.ruoyi.reservationserver.entity.Court> courts = courtService1.list();
        for(com.ruoyi.reservationserver.entity.Court c :courts){
            CourtPojo courtPojo = new CourtPojo();
            CourtType courtType = courtTypeService.queryById(c.getCourtTypeId());
            courtPojo.setCourtTypeName(courtType.getTypeName());
            courtPojo.setCourtId(c.getCourtId());
            courtPojo.setCapacity(c.getCapacity());
            Stadium stadium = stadiumService.queryById(c.getStadiumId());
            courtPojo.setStadiumName(stadium.getStadiumName());
            courtPojo.setCourtStatus(c.getCourtStatus());
            courtPojo.setCourtName(c.getCourtName());
            courtPojos.add(courtPojo);
        }

        return Result.success(courtPojos);
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @GetMapping("/del")
    public Result deleteById(@RequestParam("courtId") Integer id) {

        try {
            com.ruoyi.reservationserver.entity.Court court=courtService1.queryById(id);
            QueryWrapper<CourtStatistic> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("stadium_id",court.getStadiumId());

            CourtStatistic courtStatistic = courtStatisticService.getOne(queryWrapper);
            if (courtStatistic !=null){
                Integer courtNum = courtStatistic.getCourtNum()-1;
                courtStatistic.setCourtNum(courtNum);
                courtStatisticService.update(courtStatistic);
                this.courtService1.deleteById(id);
            }else {
                return Result.error("500","不存在该球馆");
            }


            return Result.success();
        }catch (Exception e) {
            System.out.println(e);
            return Result.error("删除失败");
        }

    }

}
